// 音乐播放器系统
document.addEventListener('DOMContentLoaded', function() {
    // 音乐播放器状态
    const musicPlayer = {
        audioContext: null,
        audioElement: null,
        analyser: null,
        isPlaying: false,
        currentTrackIndex: 0,
        tracks: [
            {
                name: "说好的幸福呢",
                url: "https://music.163.com/song?id=2670431682&uct2=U2FsdGVkX1/Wqacrp1ZBtnrj5VQ+iVhJTIk5f2gu7bs="
            },
            {
                name: "温柔小提琴",
                url: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3"
            },
            {
                name: "爱的旋律",
                url: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3"
            }
        ],
        init: function() {
            // 创建音频元素
            this.audioElement = new Audio();
            this.audioElement.loop = true;
            this.loadTrack(this.currentTrackIndex);
            
            // 设置音频上下文
            this.setupAudioContext();
            
            // 绑定音乐切换按钮事件
            this.bindEvents();
        },
        setupAudioContext: function() {
            try {
                this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
                const source = this.audioContext.createMediaElementSource(this.audioElement);
                this.analyser = this.audioContext.createAnalyser();
                
                source.connect(this.analyser);
                this.analyser.connect(this.audioContext.destination);
                
                this.analyser.fftSize = 256;
            } catch (e) {
                console.error('Web Audio API is not supported', e);
            }
        },
        loadTrack: function(index) {
            this.currentTrackIndex = index;
            this.audioElement.src = this.tracks[index].url;
            
            // 预加载音乐
            this.audioElement.load();
        },
        bindEvents: function() {
            const toggleBtn = document.getElementById('musicToggle');
            if (toggleBtn) {
                toggleBtn.addEventListener('click', () => this.togglePlayback());
            }
            
            // 当页面不可见时暂停音乐
            document.addEventListener('visibilitychange', () => {
                if (document.hidden) {
                    this.pause();
                }
            });
        },
        togglePlayback: function() {
            if (this.isPlaying) {
                this.pause();
            } else {
                this.play();
            }
        },
        play: function() {
            if (this.audioContext && this.audioContext.state === 'suspended') {
                this.audioContext.resume();
            }
            
            this.audioElement.play()
                .then(() => {
                    this.isPlaying = true;
                    this.updateButtonState();
                    this.startVisualization();
                })
                .catch(error => {
                    console.error('Playback failed:', error);
                    // 显示需要用户交互的提示
                    alert('请点击页面任意位置以允许播放音乐');
                });
        },
        pause: function() {
            this.audioElement.pause();
            this.isPlaying = false;
            this.updateButtonState();
            this.stopVisualization();
        },
        nextTrack: function() {
            this.pause();
            this.currentTrackIndex = (this.currentTrackIndex + 1) % this.tracks.length;
            this.loadTrack(this.currentTrackIndex);
            this.play();
        },
        updateButtonState: function() {
            const toggleBtn = document.getElementById('musicToggle');
            if (toggleBtn) {
                toggleBtn.textContent = this.isPlaying ? 
                    `🎵 ${this.tracks[this.currentTrackIndex].name}` : 
                    '🎵 播放音乐';
            }
        },
        startVisualization: function() {
            if (!this.analyser) return;
            
            const canvas = document.createElement('canvas');
            canvas.className = 'music-visualizer';
            canvas.width = 200;
            canvas.height = 60;
            
            const existingCanvas = document.querySelector('.music-visualizer');
            if (existingCanvas) {
                existingCanvas.remove();
            }
            
            const toggleBtn = document.getElementById('musicToggle');
            if (toggleBtn) {
                toggleBtn.insertAdjacentElement('afterend', canvas);
            }
            
            const canvasCtx = canvas.getContext('2d');
            const bufferLength = this.analyser.frequencyBinCount;
            const dataArray = new Uint8Array(bufferLength);
            
            function draw() {
                requestAnimationFrame(draw);
                
                if (!musicPlayer.isPlaying) return;
                
                musicPlayer.analyser.getByteFrequencyData(dataArray);
                
                canvasCtx.fillStyle = 'rgba(255, 255, 255, 0.1)';
                canvasCtx.fillRect(0, 0, canvas.width, canvas.height);
                
                const barWidth = (canvas.width / bufferLength) * 2.5;
                let x = 0;
                
                for (let i = 0; i < bufferLength; i++) {
                    const barHeight = dataArray[i] / 2;
                    
                    canvasCtx.fillStyle = `rgb(${barHeight + 100}, 50, 50)`;
                    canvasCtx.fillRect(x, canvas.height - barHeight, barWidth, barHeight);
                    
                    x += barWidth + 1;
                }
            }
            
            draw();
        },
        stopVisualization: function() {
            const canvas = document.querySelector('.music-visualizer');
            if (canvas) {
                canvas.remove();
            }
        }
    };
    
    // 初始化音乐播放器
    musicPlayer.init();
    
    // 暴露音乐播放器给全局
    window.musicPlayer = musicPlayer;
    
    // 点击页面任意位置恢复音频上下文（解决浏览器自动播放策略）
    document.body.addEventListener('click', function initAudioContext() {
        if (musicPlayer.audioContext && musicPlayer.audioContext.state === 'suspended') {
            musicPlayer.audioContext.resume();
        }
        document.body.removeEventListener('click', initAudioContext);
    });
});

// 音乐可视化样式
const musicVisualizerStyle = document.createElement('style');
musicVisualizerStyle.textContent = `
    .music-visualizer {
        display: block;
        margin: 10px auto;
        border-radius: 10px;
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(5px);
    }
`;
document.head.appendChild(musicVisualizerStyle);